package boot.spring.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import boot.spring.entity.Users;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import boot.spring.entity.Role;
import boot.spring.mapper.UserInfoMapper;
import boot.spring.service.RoleService;
import boot.spring.service.UserInfoService;
import boot.spring.util.JwtUtils;
import boot.spring.util.MD5Utils;
import boot.spring.util.Result;

@Service
public class UserInfoServiceImpl implements UserInfoService {
	/*创建日期对象*/
	LocalDateTime localDateTime = LocalDateTime.now();
	String date=localDateTime+"";
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private RoleService roleService;
	
	Result r = null;
	@Override
	public Result login(Users u) {
		//获取subject操作主体
		Subject subject=SecurityUtils.getSubject();
		System.out.println(u.getUloginname()+u.getUpassword());
		//设置登录的用户名和密码
		UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(u.getUloginname(), u.getUpassword());
		//登录
		try {
			subject.login(usernamePasswordToken);
			//获取操作主体
			Users user = (Users) subject.getPrincipal();
			//UserInfo user = getUserByName(u.getName());
			if(user!=null) {
				//获取用户的角色
				List<Role> rList = roleService.getRoleByUid(user.getUid());
				//获取数据库中加密后的密码
				String pwdToken = user.getUpassword();
				System.out.println(pwdToken);
				//获取用户输入的密码
				String pwd = u.getUpassword();
				//验证密码是否有效
				boolean verify = MD5Utils.verify(pwd, pwdToken);
				if(user.getIflock().equals("1")) {
					//如果用户数据库中的Iflock列的值为1则说明被锁定了，这时要抛出异常，如果为0则正常
					throw new LockedAccountException();
				}else if(!verify){
					//如果输入的密码和数据库中的密码不一致（false）则抛出IncorrectCredentialsException异常
					throw new IncorrectCredentialsException();
				}else if(verify){
					//设置用户的角色
					user.setrList(rList);
					//生成token
					String sign = JwtUtils.sign(u.getUloginname());
					//重置用户登录错密码的次数
					Users us=new Users(user.getUid(),"0",0,user.getLocktime(),user.getPawresettime());
					/*调用getUpUser方法*/
					Integer a=getUpUser(us);
					//返回数据
					r = new Result(1,sign,1000,user);
				}
			}else {
				r = new Result(0,"登录失败");
			}
		} catch (UnknownAccountException e) {
			return new Result(0, "该用户不存在！");
		} catch (LockedAccountException e) {

			return new Result(0, "账户已被锁定！");
		}catch (IncorrectCredentialsException e) {

			//获取操作主体
			Users user = (Users) subject.getPrincipal();
			/*如果当前用户密码输入次数再加上1的次数小于5的话那么就不会被锁定*/
			if((user.getErrorcount()+1)<5){
				Users us=new Users(user.getUid(),"0",(user.getErrorcount()+1),null,null);
				/*调用getUpUser方法*/
				Integer a=getUpUser(us);
			}else if((user.getErrorcount()+1)>=5){/*如果当前用户密码输入次数再加上1大于等于5的话那么就锁定*/
				Users us=new Users(user.getUid(),"1",(user.getErrorcount()+1),date,null);
				/*调用getUpUser方法*/
				Integer a=getUpUser(us);
			}

			/*密码错误对错误次数字段加1*/
			return new Result(0, "密码错误"+(user.getErrorcount()+1)+"次！错误5次将锁定账号。");
		}
		return r;
	}

	@Override
	public Result register(Users u) {
		//获取用户输入的密码
		String password = u.getUpassword();
		//通过MD5生成密钥
		String generate = MD5Utils.generate(password);
		//把密钥存入数据库
		u.setUpassword(generate);
		//添加用户
		int i = userInfoMapper.register(u);
		if(i > 0) {
			r = new Result(0,"注册成功");
		}else {
			r = new Result(0,"注册失败");
		}
		return r;
	}
	
	@Override
	public Users getUserByName(String uname) {
		return userInfoMapper.getUserByName(uname);
	}

	@Override
	public Result getAllUser() {
		List<Users> allUser = userInfoMapper.getAllUser();
		if(allUser.size()>0) {
			r = new Result(0,"查询成功",1000,allUser);
		}else {
			r = new Result(0,"查询失败");
		}
		return r;
	}

	@Override/*根据用户的id去修改用户密码输入错的次数和是否锁定以及锁定时间*/
	public Integer getUpUser(Users u) {
		return userInfoMapper.getUpUser(u);
	}

	@Override
	public Result getUppawUer(String upaw,String upaw2,String uloginname) {
		Users user = userInfoMapper.getUserByName(uloginname);//根据用户登录名查询用户信息

		String pwdToken=user.getUpassword();
		//验证密码是否有效
		boolean verify = MD5Utils.verify(upaw, pwdToken);
		System.out.println("verify++++"+verify);
		if(!verify){
			r=new Result(1,"密码不一致");
		}else{

			/*创建users对象把用户登录名和要修改的密码存进去*/
			Users u=new Users();
			u.setUpassword(MD5Utils.generate(upaw2));/*把密码加盐加密存到数据库里面*/
			u.setUloginname(uloginname);/*登录名*/
			Integer up=userInfoMapper.getUppawUer(u);/*调用修改密码的持久层方法*/
			if (up==1){
				r=new Result(0,"修改成功");
			}else{
				r=new Result(1,"修改失败");
			}
		}
		return r;
	}
}